import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
//修改为你的实体类的包名
packageName = "" //自动生成
typeMapping = [
        (~/(?i)int/)                      : "Long",
        (~/(?i)float|double|decimal|real/): "java.math.BigDecimal",
        (~/(?i)bool|boolean/)             : "Boolean",
        (~/(?i)datetime|timestamp|date|time/)  : "java.util.Date",
        (~/(?i)/)                         : "String"
]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}


def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    packageName = getPackageName(dir)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, table, className, fields) }
}

def getPackageName(dir) {
    return dir.toString().replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, table, className, fields) {
    def tableName = table.getName()
    out.println "package $packageName"
    out.println ""
    out.println "import com.iloop56.wms.dal.po.BasePO;"
    out.println "import io.swagger.annotations.ApiModelProperty;"
    out.println "import lombok.Getter;"
    out.println "import lombok.Setter;"
    out.println ""
    out.println "import javax.persistence.*;"
    out.println ""
    out.println "@Getter @Setter"
    out.println "@Entity"
    out.println "@Table(name = \"$tableName\")"
    out.println "public class $className extends BasePO {"
    out.println "    private static final long serialVersionUID = 0L;"
    out.println ""
    // 判断自增
    if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
        out.println "    @Id"
        out.println "    @GeneratedValue(strategy = GenerationType.IDENTITY)"
    }
    for (it in fields) {

        if (['is_deleted',
             'gmt_create',
             'gmt_modified',
             'create_operator_id',
             'create_operator',
             'modify_operator_id',
             'modify_operator',
             'party_id',
             'update_version',
             'ext_json',
             'remark'].contains(it.colum)) continue
        if (it.annos != "") out.println "    @ApiModelProperty(\"${it.annos}\")"
        if (it.colum != it.name) {
            out.println "    @Column(name = \"${it.colum}\")"
        }
        out.println "    private ${it.type} ${it.name};"
        out.println ""
    }
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name : javaName(col.getName(), false),
                           colum: col.getName(),
                           type : typeStr,
                           annos: col.getComment()]]
    }
}

def javaName(str, capitalize) {
    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_").replaceAll(/_/, "")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}